package com.hm.cms.service.api;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Spliterator;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.task.TaskExecutor;
import org.springframework.stereotype.Service;

import com.hm.cms.auto.SystemEnvConfigProperties;
import com.hm.cms.auto.su.R.SystemConfig;
import com.hm.cms.def.AdvertSiteEnum;
import com.hm.cms.def.ExtLlinkEnum;
import com.hm.cms.domain.QTermTaxonomyDomain;
import com.hm.cms.domain.TermTaxonomyDomain;
import com.hm.cms.repository.TermTaxonomyRepository;
import com.hm.cms.service.AdvertService;
import com.hm.cms.service.ArticleService;
import com.hm.cms.service.ExtLinkService;
import com.hm.cms.service.TermTaxonomyService;
import com.hm.cms.su.BeanUtil;
import com.hm.cms.vo.HcmsHomePageVo;
import com.hm.cms.vo.HcmsHomePageVo.WebPageNavVo;
import com.hm.cms.vo.HcmsHomePageVo.WebPageTagNavVo;
import com.hm.cms.vo.HcmsPageAdvertVo;
import com.hm.cms.vo.HcmsPageBaseInfoVo;
import com.hm.cms.vo.HcmsPageExtLinkVo;
import com.hm.cms.vo.HcmsTermTaxonomyVo;
import com.hm.common.su.bean.PageInfo.PageInfoParam;
import com.hm.common.util.DateUtil;
import com.hm.common.util.EncryptUtil.Base64;
import com.hm.common.util.FileUtil;
import com.hm.common.util.FreemakUtil;
import com.hm.common.util.StringUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * @author shishun.wang
 * @date 2017年11月30日 下午4:51:55
 * @version 1.0
 * @describe
 */
@Slf4j
@Service
public class TermApiTaxonomyServiceImpl implements TermApiTaxonomyService {

	@Autowired
	private TaskExecutor taskExecutor;

	@Autowired
	private AdvertService advertService;

	@Autowired
	private ExtLinkService extLinkService;

	@Autowired
	private TermTaxonomyService termTaxonomyService;

	@Autowired
	private ArticleService articleService;

	@Autowired
	private SystemEnvConfigProperties systemEnvConfigProperties;

	@Autowired
	private TermTaxonomyRepository termTaxonomyRepository;

	@Override
	public List<HcmsTermTaxonomyVo> loadHcmsTermTaxonomy(String parentTermTay) {
		QTermTaxonomyDomain qTermTaxonomyDomain = QTermTaxonomyDomain.termTaxonomyDomain;
		Spliterator<TermTaxonomyDomain> spliterator = null;
		if (StringUtil.isBlankOrNull(parentTermTay)) {
			spliterator = termTaxonomyRepository.findAll(qTermTaxonomyDomain.parentTermTay.isEmpty()).spliterator();
		} else {
			spliterator = termTaxonomyRepository.findAll(qTermTaxonomyDomain.parentTermTay.eq(parentTermTay.trim()))
					.spliterator();
		}

		List<HcmsTermTaxonomyVo> vos = new ArrayList<HcmsTermTaxonomyVo>();
		spliterator.forEachRemaining(item -> {
			HcmsTermTaxonomyVo vo = new HcmsTermTaxonomyVo();
			BeanUtil.copyProperties(item, vo);
			vos.add(vo);
		});

		return vos;
	}

	@Override
	public void staticTermTaxonomy() {
		taskExecutor.execute(new Runnable() {

			@Override
			public void run() {
				termTaxonomyRepository.findAll().parallelStream().forEach(termTaxonomys -> {

					Map<String, Object> model = new HashMap<String, Object>();
					{
						HcmsTermTaxonomyVo termTaxonomyVo = termTaxonomyService
								.getTermTaxonomysByCode(termTaxonomys.getTermTayCode());
						model.put("termTay", termTaxonomyVo);

						initBaseInfo(model, termTaxonomyVo.getId());
						setHeadPageAdvert(AdvertSiteEnum.HOME_HEAD_SLIDE, model);
						setExtLink(model);
						model.put("moreArticlCatalogUri", "o_term_taxonomy/pagging/show/" + termTaxonomyVo.getId());

						HcmsHomePageVo homePageVo = new HcmsHomePageVo();
						{
							homePageVo.setWebPageNavs(termTaxonomyService.loadSysNavs());
						}
						model.put("homePageInfo", homePageVo);
						model.put("basePath", systemEnvConfigProperties.getStaticHtmlDomainName());
					}

					String staticUrl = "cms-static/" + DateUtil.now4yyyyMMdd() + "/o_term_taxonomy/tags/"
							+ termTaxonomys.getId() + ".html";
					try {
						Resource resource = new ClassPathResource("/templates/article");
						File templateFolder = resource.getFile();
						// 填充模板数据、压缩数据
						String html = FreemakUtil.process(templateFolder, "article_list.ftl", model);
						String htmlPath = systemEnvConfigProperties.getStaticHtmlPath() + "/" + staticUrl;
						// 静态化完成
						FileUtil.writer(htmlPath, html, true);

						termTaxonomys.setNavUri(staticUrl);
						termTaxonomyRepository.save(termTaxonomys);
					} catch (Exception e) {
						log.error(e.getMessage(), e);
					}

				});
				log.info("静态化完成标签页");
			}
		});
	}

	private void initBaseInfo(Map<String, Object> model, String termTayId) {
		HcmsPageBaseInfoVo baseInfoVo = new HcmsPageBaseInfoVo();
		{
			baseInfoVo.setOpenLogin(systemEnvConfigProperties.isOpenLogin());
			baseInfoVo.setSiteFtInfo(
					new String(Base64.decode(systemEnvConfigProperties.getSiteFooterInfo().toCharArray())));
			baseInfoVo.setSiteShare(new String(Base64.decode(systemEnvConfigProperties.getSiteShare().toCharArray())));
			baseInfoVo.termTaxonomy(termTaxonomyService.loadHcmsTermTaxonomys());

			baseInfoVo.newestArticle(articleService
					.queryArticle(new PageInfoParam(1, SystemConfig.ARTICLE_CATALOG_SHOW_SIZE), termTayId, null));
			baseInfoVo.hotArticle(
					articleService.queryArticle(new PageInfoParam(1, SystemConfig.TAG_SHOW_SIZE), null, null));
		}

		model.put("baseInfo", baseInfoVo);
	}

	private void setExtLink(Map<String, Object> model) {
		model.put("pageExtLlink",
				new HcmsPageExtLinkVo().friendshipLink(extLinkService.loadExtLinks(ExtLlinkEnum.FRIENDSHIP_LINK))
						.onlineToolLink(extLinkService.loadExtLinks(ExtLlinkEnum.ONLINE_TOOL_LINK)));
	}

	private void setHeadPageAdvert(AdvertSiteEnum advertSite, Map<String, Object> model) {
		model.put("pageAdvert", new HcmsPageAdvertVo().headSlides(advertService.loadPageAdvert(advertSite)));
	}

	private void initBaseInfo(Map<String, Object> model) {
		HcmsPageBaseInfoVo baseInfoVo = new HcmsPageBaseInfoVo();
		{
			baseInfoVo.setOpenLogin(systemEnvConfigProperties.isOpenLogin());
			baseInfoVo.setSiteFtInfo(new String(Base64.decode(systemEnvConfigProperties.getSiteFooterInfo().toCharArray())));
			baseInfoVo.setSiteShare(new String(Base64.decode(systemEnvConfigProperties.getSiteShare().toCharArray())));
			baseInfoVo.termTaxonomy(termTaxonomyService.loadHcmsTermTaxonomys());

			baseInfoVo.hotArticle(articleService.queryArticle(new PageInfoParam(1, SystemConfig.TAG_SHOW_SIZE), null, null));
		}

		model.put("baseInfo", baseInfoVo);
	}
	
	@Override
	public void staticHomePage() {
		Map<String, Object> model = new HashMap<String, Object>();
		initBaseInfo(model);
		setHeadPageAdvert(AdvertSiteEnum.HOME_HEAD_SLIDE, model);
		setExtLink(model);

		HcmsHomePageVo homePageVo = new HcmsHomePageVo();
		{
			List<WebPageNavVo> pageNavs = termTaxonomyService.loadSysNavs();
			homePageVo.setWebPageNavs(pageNavs);

			List<WebPageTagNavVo> webPageTagNavs = new ArrayList<WebPageTagNavVo>();
			for (WebPageNavVo pageNav : termTaxonomyService.loadSysTermTaxos()) {
				WebPageTagNavVo vo = new WebPageTagNavVo();
				{
					vo.setTagNavName(pageNav.getName());
					vo.setShowMoreUri(pageNav.getUri());
					vo.tagNavChild(articleService.queryArticle(new PageInfoParam(1, 8), pageNav.getId(), null));
				}

				webPageTagNavs.add(vo);
			}

			homePageVo.setWebPageTagNavs(webPageTagNavs);
		}
		model.put("homePageInfo", homePageVo);
		
		String staticUrl = "cms-static/index.html";
		try {
			Resource resource = new ClassPathResource("/templates");
			File templateFolder = resource.getFile();
			// 填充模板数据、压缩数据
			String html = FreemakUtil.process(templateFolder, "index.ftl", model);
			String htmlPath = systemEnvConfigProperties.getStaticHtmlPath() + "/" + staticUrl;
			// 静态化完成
			FileUtil.writer(htmlPath, html, true);
			
			log.info("静态化完成首页");
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
	}

}
